package top.leix.springdemo.aop;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import top.leix.springdemo.mapper.OperateLogMapper;
import top.leix.springdemo.pojo.OperateLog;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 日志切面类
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    @Resource
    private HttpServletRequest request;

    @Resource
    OperateLogMapper operateLogMapper;

    @Around("@annotation(top.leix.springdemo.annotation.MyLog)")
    public Object record(ProceedingJoinPoint joinPoint) throws Throwable {
        //调用前操作
        System.out.println("切面成功进入啦~~~~~~~~");
        //获取信息
        OperateLog operateLog = new OperateLog();
        //1、获取操作人的id
        String token = request.getHeader("token");
        JWT jwt = JWTUtil.parseToken(token);

        String account = jwt.getPayload("userAccount").toString();
        System.out.println("切面获取账号：" + account);
        operateLog.setOperate_user(account);
        //2、获取执行开始时间
        operateLog.setOperate_time(new Date());

        //3、操作类名
        String className = joinPoint.getTarget().getClass().getName();
        operateLog.setClass_name(className);

        //4、操作方法名
        String method = joinPoint.getSignature().getName();
        operateLog.setMethod_name(method);

        //5、方法参数
        Object[] args = joinPoint.getArgs();
        String argString = Arrays.toString(args);
        operateLog.setMethod_params(argString);

        Long begin = System.currentTimeMillis();
        //调用目标方法
        Object result = joinPoint.proceed();
        Long end = System.currentTimeMillis();
        //操作完成时间
        Long costTime = end - begin;
        //6、方法耗时
        operateLog.setCost_time(costTime);
        //7、返回值
        String jsonStringResult = JSONObject.toJSONString(result);
        operateLog.setReturn_value(jsonStringResult);
        //完成后操作
        //记录日志
        operateLogMapper.insert(operateLog);
        return result;
    }
}
